import React from 'react';
import { createForm, setValidateLanguage } from '@formily/core';
import { createSchemaField, FormProvider } from '@formily/react';
import components from './schema-components-registed/components-biz';
import { SchemaFormRenderProps, SchemaFormRenderState, createSchema } from 'schema-form';
import _ from 'lodash';
import { storage } from '@ey-utils/utils/utils';

import {toJS} from '@formily/reactive'

import { getLocale } from 'umi';
import { getUserInfo } from '@/utils/userInfo';
import { times, plus, minus,round } from '@ey-utils/utils/numberPrecision';
import { getValidateMessage } from '@/utils/validate-rules/message';

export const createSchemaFormRender: createSchema = (
  createSchemaFieldConfig,
  formConfig,
  extProps,
) => {
  const SchemaField = createSchemaField(
    _.merge(
      {
        components: {
          ...components,
        },
        scope: {
          getUserInfo: getUserInfo,
          times,
          plus,
          minus,
          round,
          merge: _.merge,
          toJS,
          getValidateMessage,
        }
      },
      createSchemaFieldConfig,
    ),
  );
  const form = createForm(formConfig);

  setValidateLanguage(getLocale());

  const update = _.once(() => {
    const cache = storage.getItem(location.hash.slice(1));
    if (extProps?.needCache && cache?.queryKeys) {
      form.setValues({
        ...cache?.queryKeys,
      });
    }
  });
  class Render extends React.Component<SchemaFormRenderProps, SchemaFormRenderState> {
    componentDidUpdate() {
      update();
    }
    render() {
      const { schema } = this.props;
      return [
        <form className={`form-id-${form.id}`}>
          <FormProvider form={form}>
            <SchemaField schema={schema} />
          </FormProvider>
        </form>,
      ];
    }
  }
  return {
    form,
    Render: (props: SchemaFormRenderProps) => <Render {...props} />,
  };
};
